package com.demo.user.service.impl;

import com.demo.user.entity.User;
import com.demo.user.mapper.UserMapper;
import com.demo.user.service.UserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现类
 * 实现用户登录、获取用户信息、登出等功能
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.expiration}")
    private Long jwtExpiration;
    
    /**
     * 用户Mapper接口
     */
    private final UserMapper userMapper;

    /**
     * 用户登录
     * 
     * @param username 用户名
     * @param password 密码
     * @return 登录结果，包含token
     */
    @Override
    public Object login(String username, String password) {
        // 从数据库查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("message", "用户名或密码错误");
            return result;
        }

        // 生成JWT令牌
        String token = generateToken(user);

        // 返回登录成功信息
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "登录成功");
        result.put("token", token);
        return result;
    }

    /**
     * 获取当前用户信息
     * 
     * @return 用户信息
     */
    @Override
    public User getCurrentUser() {
        // 从SecurityContext中获取用户名
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username;
        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else {
            username = principal.toString();
        }
        
        // 从数据库查询用户信息
        return userMapper.selectByUsername(username);
    }

    /**
     * 用户登出
     * 
     * @return 登出结果
     */
    @Override
    public Object logout() {
        // 实际应清除用户会话
        // 这里简化处理，直接返回成功信息
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "登出成功");
        return result;
    }

    /**
     * 生成JWT令牌
     * 
     * @param user 用户信息
     * @return JWT令牌
     */
    private String generateToken(User user) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + jwtExpiration);

        return Jwts.builder()
                .setSubject(user.getUsername())
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .claim("role", user.getRole())
                .signWith(Keys.hmacShaKeyFor(jwtSecret.getBytes()), SignatureAlgorithm.HS512)
                .compact();
    }
}